# -*- coding: utf-8 -*-
"""
Created on Fri Jul  5 08:45:32 2019

@author: frankwin7
"""
import pandas as pd
import statistics as stat
from statsmodels.tsa.stattools import coint
from datetime import datetime, timedelta
import os.path  # To manage paths
import sys  # To find out the script name (in argv[0])
#import backtrader as bt
modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
datapath = os.path.join(modpath, '../backtrader/datas/orcl-1995-2014.txt')
'''
data = bt.feeds.YahooFinanceCSVData(
        dataname=datapath,
        # Do not pass values before this date
        fromdate=datetime(2000, 1, 1),
        # Do not pass values before this date
        todate=datetime(2000, 12, 31),
        # Do not pass values after this date
        reverse=False)
'''
dataframe = pd.read_csv(datapath, index_col = 0,#'bitfinex_BTCUSD_min_20180601_20190531.csv'
                        parse_dates=True)

start_time = '2000-01-01'
start_date_time = datetime.strptime(start_time, "%Y-%m-%d")
n = 24
pvalue_list = []
diff_upper_list = []
diff_lower_list = []
spread_pecent_list = []
lower_list = []
upper_list = []
for i in range(n):
    middle_date_time = start_date_time + timedelta(30)
    #middle_date_time = datetime.strptime('2018-08-01', "%Y-%m-%d")
    price_s = dataframe[start_date_time : middle_date_time]['Close']
    span = 2
    ema_s = price_s.ewm(span = span).mean()
    ema_s = ema_s.rename('EMA')
    concat_df = pd.concat([price_s, ema_s], axis = 1)
    concat_df_nona = concat_df.dropna()
    score, pvalue, _ = coint(concat_df_nona['Close'], concat_df_nona['EMA'])
    pvalue_list.append(pvalue)
    concat_df_nona['spread'] = concat_df_nona['Close'] - concat_df_nona['EMA']
    concat_df_nona['spread_pecent'] = concat_df_nona['spread'] / concat_df_nona['EMA']
    mean = concat_df_nona['spread_pecent'].mean()
    std = concat_df_nona['spread_pecent'].std()
    max = concat_df_nona['spread_pecent'].max()
    min = concat_df_nona['spread_pecent'].min()
    spread_pecent_list.append(concat_df_nona['spread_pecent'])
    upper = mean + 1.96 * std
    lower = mean - 1.96 * std
    upper_list.append(upper)
    lower_list.append(lower)
    if i == 0:
        precious_upper = upper
        precious_lower = lower
    diff_upper = upper - precious_upper
    diff_lower = lower - precious_lower
    diff_upper_list.append(diff_upper)
    diff_lower_list.append(diff_lower)
    precious_upper = upper
    precious_lower = lower
    start_date_time = middle_date_time
upper_mean = stat.mean(upper_list)
lower_mean = stat.mean(lower_list)
diff_upper_mean = stat.mean(diff_upper_list)
diff_lower_mean = stat.mean(diff_lower_list)
print('upper_mean' + str(upper_mean) + ',lower_mean' + str(lower_mean))
print('diff_upper_mean' + str(diff_upper_mean) + ',diff_lower_mean' + str(diff_lower_mean))
#print('max:' + str(max) + ', upper:' + str(upper) + ',lower:' + str(lower) + ',min:' + str(min))
#score, pvalue, _ = coint(concat_df_nona['2018-06-01':'2018-07-01']['close'], concat_df_nona['2018-06-01':'2018-07-01']['EMA'])
pvalue_mean = stat.mean(pvalue_list)
print('pvalue_mean' + str(pvalue_mean))
spread_pecent_list[1].plot()
print('upper_list0:' + str(upper_list[1]) + 'lower_list0:' + str(lower_list[1]))
